package org.server.provider;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;

import org.server.interfaces.service.UserService;
import org.server.provider.service.impl.UserServiceImpl;

public class Server {
	
	@SuppressWarnings({ "unchecked", "rawtypes", "resource" })
	public static void run() {
		try {
			ServerSocket server = new ServerSocket(8888);
			while(true) {
				Socket socket = server.accept();
				ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
				
				//读取请求参数
				String interfaceName = objectInputStream.readUTF();
				System.out.println("interfacename:"+interfaceName);
				String methodName = objectInputStream.readUTF();
				System.out.println("methodName:"+methodName);
				Class[] parameterTypes = (Class[])objectInputStream.readObject();
				Object[] methodArgs = (Object[])objectInputStream.readObject();
				
				Class clazz = interfaceName.equals(UserService.class.getName()) ? UserServiceImpl.class : null;
				Method method = clazz.getMethod(methodName, parameterTypes);
				Object result = method.invoke(clazz.newInstance(), methodArgs);
				
				ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
				outputStream.writeObject(result);
				outputStream.flush();
				objectInputStream.close();
				outputStream.close();
				socket.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
